<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="treeName"
            placeholder="请输入查询名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
          />
        </div>
        <el-cascader
          style="width: 100%; margin-top: 15px"
          v-model="departMajor"
          :options="departMajorOptions"
          :props="departMajorProps"
          @change="getLeftTree"
        ></el-cascader>
        <div class="head-container" style="margin-top: 15px">
          <el-tree
            ref="tree"
            :data="leftTreeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col> -->
      <leftPanel treeType="knowledge" @leftClick="getTreeNotes" />
      <el-col :span="20" :xs="24">
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
          <el-form-item label="知识点" prop="knowledgeName">
            <el-input v-model="queryParams.knowledgeName" placeholder="请输入知识点名称" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:juanKnowledge:add']" type="primary" plain icon="el-icon-plus" size="mini" :disabled="!queryParams.chapterId || queryParams.treeType !== 'chapter'" @click="handleAdd"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button v-hasPermi="['system:juanKnowledge:import']" type="info" plain icon="el-icon-upload2" size="mini" :disabled="!queryParams.chapterId" @click="handleImport"
              >导入</el-button
            >
          </el-col>

          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:juanKnowledge:export']"
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              :disabled="!queryParams.chapterId"
              @click="handleExport"
              >导出</el-button
            >

          </el-col>
          <right-toolbar :show-search.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table
        :row-class-name="tableRowClassName"
          class="dataTable"
          v-if="refreshTable"
          v-loading="loading"
          :data="juanKnowledgeList"
          row-key="knowledgeId"
          :default-expand-all="false"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @cell-click="handleTableCellClick"
        >
          <el-table-column label="编号" align="left" prop="knowledgeCode" width="200"/>
          <el-table-column label="名称" align="left" prop="knowledgeName" width="220">
            <template slot-scope="scope">
              <el-input
                size="small"
                v-model="scope.row.knowledgeName"
                v-show="scope.row.showEdit"
                @change="handleInputChange($event, scope)"
                @blur="handleInputBlur(scope.row)">
              </el-input>
              <span v-show="!scope.row.showEdit">{{scope.row.knowledgeName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="排序" align="center" prop="knowledgeSort" width="120">
            <template slot-scope="scope">
              <el-input
                size="small"
                v-model="scope.row.knowledgeSort"
                v-show="scope.row.showEditSort"
                @change="handleInputChangeSort($event, scope)"
                @blur="handleInputBlurSort(scope.row)">
              </el-input>
              <span v-show="!scope.row.showEditSort">{{ scope.row.knowledgeSort }}</span>
              <!-- <sort-arrow
                :disabledUp="scope.row._isFirst"
                :disabledDown="scope.row._isLast"
                @moveUp="sortMove(scope.row, 'up')"
                @moveDown="sortMove(scope.row, 'down')"
              /> -->
            </template>
          </el-table-column>
          <!-- <el-table-column label="排序" align="center" prop="knowledgeSort" /> -->

          <el-table-column label="重要性" align="center" prop="knowledgeImportance">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.importance" :value="scope.row.knowledgeImportance" />
            </template>
          </el-table-column>
          <el-table-column label="描述" align="center" prop="knowledgeDes" />
          <el-table-column label="创建人" align="center" prop="createdBy" />
          <el-table-column label="创建时间" align="center" prop="createdTime" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
<!--          <el-table-column label="更新人" align="center" prop="updatedBy" />-->
<!--          <el-table-column label="更新时间" align="center" prop="updatedTime" width="150">-->
<!--            <template slot-scope="scope">-->
<!--              <span>{{ parseTime(scope.row.updatedTime, "{y}-{m}-{d}") }}</span>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" width="160">
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['system:juanKnowledge:add']"
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="handleBeforeAdd(scope.row)"
              >前面插入</el-button
              >
<!--              <el-button-->
<!--                v-hasPermi="['system:juanKnowledge:add']"-->
<!--                size="mini"-->
<!--                type="text"-->
<!--                icon="el-icon-plus"-->
<!--                @click="handleAdd(scope.row)"-->
<!--              >新增子项</el-button-->
<!--              >-->
              <el-button
                v-hasPermi="['system:juanKnowledge:edit']"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                v-hasPermi="['system:juanKnowledge:remove']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 添加或修改知识点对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="知识点" prop="knowledgeParentId">
          <treeselect v-model="form.knowledgeParentId" :options="treeOptions" :normalizer="normalizer" placeholder="请选择知识点" :disabled="isEdit"/>
        </el-form-item>
        <el-form-item label="章节" prop="chapterId">
          <el-select v-model="form.chapterId" placeholder="请选择章节" style="width: 100%" :disabled="isEdit">
            <el-option
              v-for="item in chapterList"
              :key="item.id"
              :label="item.treeName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="knowledgeName">
          <el-input maxlength="30" v-model="form.knowledgeName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="重要性" prop="knowledgeImportance">
          <el-select v-model="form.knowledgeImportance" placeholder="请选择重要性" clearable>
           <el-option v-for="(dict, index) in dict.type.importance" :key="index" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
<!--        <el-form-item label="内容">-->
<!--          <editor v-model="form.knowledgeContent" :min-height="192" />-->
<!--        </el-form-item>-->
        <el-form-item label="描述" prop="knowledgeDes">
          <el-input maxlength="200" v-model="form.knowledgeDes" placeholder="请输入描述" />
        </el-form-item>
<!--        <el-form-item label="排序" prop="knowledgeSort">-->
<!--          <el-input v-model="form.knowledgeSort" placeholder="请输入排序" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 知识点导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :data="uploadData"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"  href="http://127.0.0.1:8075/static/public/zhishidian.xlsx"
          >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import { listJuanKnowledge, getJuanKnowledge, delJuanKnowledge, addJuanKnowledge, updateJuanKnowledge, juanKnowledgeDrag } from "@/api/system/juanKnowledge";
import { chapterTree } from "../../../api/system/juanKnowledge";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {importData} from "@/api/system/juanKnowledge";


import {  courseTreeList as departMajorTree } from '@/api/system/juanChapter'
import {getToken} from "@/utils/auth";
import {treeRowToValue} from "@/utils";
export default {
  name: "JuanKnowledge",
  dicts: ['importance'],
  components: {
    Treeselect,
  },
  data() {
    return {
      departMajor: null,
      departMajorOptions: null,
      departMajorProps: {
        label: 'treeName',
        value: 'id',
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 知识点表格数据
      juanKnowledgeList: [],
      // 知识点树选项
      treeOptions: [],
      //章节下拉选择项
      chapterTreeOptions: [],
      // 弹出层标题
      title: "",
      //知识点名称
      treeName: undefined,
      // 左侧树选项
      leftTreeOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        knowledgeParentId: undefined,
        chapterId: undefined,
        treeType: undefined,
        knowledgeCode: undefined,
        knowledgeName: undefined,
        knowledgeContent: undefined,
        knowledgeDes: undefined,
        createdBy: undefined,
        createdTime: undefined,
        updatedBy: undefined,
        updatedTime: undefined,
        parentIds: undefined,
        knowledgeSort: undefined,
        knowledgeImportance: undefined,
      },
      currentSort: undefined,
      // 表单参数
      isEdit: true,
      form: {},
      defaultProps: {
        children: "children",
        label: "treeName",
      },
      // 表单校验
      rules: {
        knowledgeId: [{ required: true, message: "ID不能为空", trigger: "blur" }],
        knowledgeParentId: [{ required: true, message: "父节点不能为空", trigger: "blur" }],
        chapterId: [{ required: true, message: "章节ID不能为空", trigger: "blur" }],
        knowledgeName: [{ required: true, message: "名称不能为空", trigger: "blur" }],
      },
      // 知识点导入参数
      upload: {
        // 是否显示弹出层（专业导入）
        open: false,
        // 弹出层标题（专业导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: "http://127.0.0.1:8075/system/juanKnowledge/importData",
      },
      //上传携带参数
      uploadData:{},
      chapterList: []
    };
  },
  watch: {
    // 根据名称筛选知识点树
    treeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    // this.getList();
    // this.getLeftTree();
    // this.getDepartMajorOptions();
    // this.loading = false;
  },
  mounted() {
    // this.rowDrop()
  },
  methods: {
    tableRowClassName({row, rowIndex}) {
        if(row._level != 0){
          return 'row-bg'
        }
        return '';
    },
    // 树节点单击事件
    getTreeNotes(obj) {
      if (obj) {
        console.log(JSON.parse(JSON.stringify(obj)))
        this.reposId = obj.departMajor[2];
        this.courseId = obj.departMajor[2];
        this.chapterList = [obj.treeNode]
        this.queryParams.chapterId = obj.treeNode.id;
        this.queryParams.treeType = obj.treeNode.treeType;
        this.chapterTreeOptions = obj.selectOptions;


        this.handleQuery();
      } else {
        this.queryParams.chapterId = undefined;
        this.queryParams.treeType = undefined;
      }
    },

    /** 查询知识点列表 */
    getList() {
      this.loading = true;
      listJuanKnowledge(this.queryParams).then((response) => {
        this.juanKnowledgeList = this.handleTree(response.data, "knowledgeId", "knowledgeParentId");
        //console.log(this.juanKnowledgeList)
        this.loading = false;
      });
    },
    /** 查询章节树 */
    getLeftTree() {
      let departId = this.departMajor[0];
      let majorId = this.departMajor[1];
      let courseId = this.departMajor[2];
      chapterTree(courseId).then((response) => {
        this.leftTreeOptions = response.data;
        this.chapterTreeOptions = this.buildList(response.data);
      });
    },
    /** 查询树结构 */
    getDepartMajorOptions() {
      departMajorTree().then((response) => {
        this.departMajorOptions = response.data;
        let departId = null, majorId = null, courseId = null;
        if( response.data && response.data.length > 0) {
          departId = response.data[0].id;
          if(response.data[0].children.length > 0) {
            majorId = response.data[0].children[0].id

            if(response.data[0].children[0].children && response.data[0].children[0].children.length > 0) {
              courseId = response.data[0].children[0].children[0].id
            }
          }
        }
        this.departMajor = [departId, majorId, courseId]
        this.getLeftTree();
      });
    },
    /** 递归查询章节下拉树选项 */
    buildList(tree) {
      let list = []
      for (let i in tree) {
        list.push(tree[i]);
        if (tree[i].children.length !== 0) {
          list.push(...this.buildList(tree[i].children))
        }
      }
      return list;
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.treeName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.chapterId = data.id;
      this.queryParams.treeType = data.treeType;
      this.handleQuery();
    },
    /** 转换知识点树表结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.knowledgeId,
        label: node.knowledgeName,
        children: node.children,
      };
    },
    /** 查询知识点下拉树 */
    getTreeSelect() {
      listJuanKnowledge(this.queryParams).then((response) => {
        this.treeOptions = [];
        const data = { knowledgeId: 0, knowledgeName: "顶级节点", children: [] };
        data.children = this.handleTree(response.data, "knowledgeId", "knowledgeParentId");
        this.treeOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        knowledgeId: undefined,
        knowledgeParentId: undefined,
        knowledgeName: undefined,
        chapterId: undefined,
        knowledgeCode: undefined,
        knowledgeContent: undefined,
        knowledgeDes: undefined,
        createdBy: undefined,
        createdTime: undefined,
        updatedBy: undefined,
        updatedTime: undefined,
        parentIds: undefined,
        knowledgeSort: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeSelect();
      if (row != null && row.knowledgeId) {
        this.form.knowledgeParentId = row.knowledgeId;
      } else {
        this.form.knowledgeParentId = 0;
      }
      this.form.chapterId = this.queryParams.chapterId;

      this.open = true;
      this.title = "添加知识点";
    },
    handleBeforeAdd(row) {
      this.reset();
      this.getTreeSelect();
      if (row != null && row.knowledgeParentId) {
        this.form.knowledgeParentId = row.knowledgeParentId;
      } else {
        this.form.knowledgeParentId = 0;
      }
      this.form.knowledgeSort = row.knowledgeSort;
      this.form.chapterId = this.queryParams.chapterId;

      this.open = true;
      this.title = "添加知识点";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      this.getTreeSelect();
      if (row != null) {
        this.form.knowledgeParentId = row.knowledgeId;
      }
      getJuanKnowledge(row.knowledgeId).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改知识点";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.knowledgeId != null) {
            updateJuanKnowledge(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addJuanKnowledge(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除？')
        .then(() => {
          this.loading = true;
          return delJuanKnowledge(row.knowledgeId);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/juanKnowledge/export",
        {
          ...this.queryParams,
        },
        `知识点_${new Date().getTime()}.xlsx`
      );
    },

    /** 导入按钮操作 */
    handleImport(){
      this.upload.title = "知识点导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      if(response.code === 200){
        this.upload.open = false;
        this.$alert(
          "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + "导入成功" + "</div>",
          "导入结果",
          { dangerouslyUseHTMLString: true }
        );
        this.getList();
      }else{
        this.$modal.msgError(response.msg);
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.uploadData.chapterId = this.queryParams.chapterId;
      this.uploadData.treeType = this.queryParams.treeType;
      this.$refs.upload.submit();
    },
    handleTableCellClick(row, column, cell, event) {
      if(column.property === 'knowledgeName') {
        this.$set(row, 'showEdit', true)
        this.$set(row, 'disabled', false)
        this.$nextTick(() => {
          cell?.children?.[0]?.children?.[0]?.children?.[0]?.focus();
        });
      }
      if(column.property === 'knowledgeSort') {
        const rowData = JSON.parse(JSON.stringify(row));
        this.$set(row, 'showEditSort', true)
        this.$set(row, 'disabled', false)
        this.$set(this, 'currentSort', rowData.knowledgeSort)
        this.$nextTick(() => {
          cell?.children?.[0]?.children?.[0]?.children?.[0]?.focus();
        });
      }
    },
    handleInputChange(value, {row, column}) {
      if(value) {
        this.$set(row, 'disabled', true)
        updateJuanKnowledge({
          ...row,
          knowledgeName: value
        })
          .then((response) => {
            this.$set(row, 'showEdit', false)
            this.$modal.msgSuccess("修改成功");
          })
          .finally(() => {
            this.$set(row, 'disabled', false)
          });
      }
    },
    handleInputBlur(row) {
      this.$set(row, 'showEdit', false)
    },

    handleInputChangeSort(value, {row, column}) {
      if(value) {
        this.$set(row, 'disabled', true)
        let option = {
          currentSort: this.currentSort,
          targetSort: row.knowledgeSort,
          chapterId: row.chapterId,
          knowledgeParentId: row.knowledgeParentId,
        }
        juanKnowledgeDrag(option)
          .then((response) => {
            this.$set(row, 'showEditSort', false)
            this.$modal.msgSuccess("修改成功");
            this.getList();
          })
          .finally(() => {
            this.$set(row, 'disabled', false)
          });
      }
    },
    handleInputBlurSort(row) {
      this.$set(row, 'showEditSort', false)
    },

    //行拖拽
    rowDrop() {
      const tbody = document.querySelector('.dataTable tbody')
      Sortable.create(tbody, {
        draggable: '.el-table__row',
        onEnd: ({ newIndex, oldIndex }) => {
          console.log("newIndex: " + newIndex, "oldIndex: " + oldIndex)
          // const currRow = this.juanKnowledgeList.splice(oldIndex, 1)[0]
          // this.juanKnowledgeList.splice(newIndex, 0, currRow)
          // let nextRow = this.juanKnowledgeList[oldIndex + 1]
          // console.log(currRow, nextRow)
          // let option = {
          //   currentSort: currRow,
          //   targetSort: '1',
          //   chapterId: '1595689193927974913',
          //   knowledgeParentId: '0'
          // }
          // juanKnowledgeDrag(option).then().catch()
        }
      })
    },
    sortMove(row, postion) {
      let targetRows = row._rows.slice(0, row._rows.length - 1);
      if(postion === 'up') {
        targetRows.push(row._row - 1);
      } else if(postion === 'down') {
        targetRows.push(row._row + 1);
      }
      let targetRow = treeRowToValue(this.juanKnowledgeList, targetRows);
      console.log(targetRow)
      let option = {
        currentSort: row.knowledgeSort,
        targetSort: targetRow.knowledgeSort,
        chapterId: row.chapterId,
        knowledgeParentId: row.knowledgeParentId,
      }
      juanKnowledgeDrag(option).then( res=> {
        this.getList();
      }).catch()
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep{
  .el-table{
    .row-bg{
      background-color: #e8f4ff87;
    }
  }
}

</style>
